//
//  ScanViewController.m
//  WE
//
//  Created by iMacOne on 15/11/25.
//  Copyright © 2015年 UNOHACHA. All rights reserved.
//

#import "ScanViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ToolUtil.h"
#import "Size.h"
@interface ScanViewController ()<AVCaptureMetadataOutputObjectsDelegate>
{
    UIView *scannerView;
    UIView *middleLine;
    NSTimer *timer;
}
@property (strong, nonatomic)AVCaptureDevice *device;
@property (strong, nonatomic)AVCaptureDeviceInput *input;
@property (strong, nonatomic)AVCaptureMetadataOutput *output;
@property (strong, nonatomic)AVCaptureSession *session;
@property (strong, nonatomic)AVCaptureVideoPreviewLayer *preview;
@end

@implementation ScanViewController


- (void)viewWillDisappear:(BOOL)animated
{
    [timer invalidate];
    timer = nil;
    [super viewWillDisappear:animated];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupCamera];
    self.navigationItem.title = @"扫一扫";

    self.view.backgroundColor = [UIColor whiteColor];
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 40, 20);
    [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [btn setTitle:@"关闭" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
//    btn.backgroundColor = DEBUG_CLOLR;
    
    UIBarButtonItem * back = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = back;
    
    int scannerSize = WindowWidth * 0.66, scanner_x = (WindowWidth - scannerSize) / 2, scanner_y = scanner_x;
    scannerView = [[UIView alloc]initWithFrame:CGRectMake(scanner_x, scanner_y, scannerSize, scannerSize)];
    UIView *body = [[UIView alloc] initWithFrame:CGRectMake(0, 64, WindowWidth, WindowHeight - 64)];
    body.backgroundColor = [UIColor clearColor];
    [self.view addSubview:body];
    [self createBorder:body];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerThread) userInfo:nil repeats:YES];
    
}
- (void)clickBtn:(UIButton *)btn
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)setupCamera
{
    // Device
    self.device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    self.input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    self.output = [[AVCaptureMetadataOutput alloc]init];
    [self.output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    self.session = [[AVCaptureSession alloc]init];
    [self.session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([self.session canAddInput:self.input])
    {
        [self.session addInput:self.input];
    }
    if ([self.session canAddOutput:self.output])
    {
        [self.session addOutput:self.output];
    }
    
    // 条码类型
    self.output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    
    // Preview
    self.preview = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.videoGravity =AVLayerVideoGravityResizeAspectFill;
    self.preview.frame =CGRectMake(0,taskbar_height+title_height+1,self.view.frame.size.width,self.view.frame.size.height);
    [self.view.layer insertSublayer:self.preview atIndex:0];
    
    // Start
    
    [self.session startRunning];
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0) {
        AVMetadataMachineReadableCodeObject *metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    [_session stopRunning];
            [self.delegate scanResult:stringValue];
    [self.navigationController popViewControllerAnimated:YES];
//    [self dismissViewControllerAnimated:NO completion:^{
//        [_session stopRunning];
//        [self.delegate scanResult:stringValue];
//    }];
}

// 创建4个直角和中线
- (void)createBorder:(UIView*)body {
    int scanner_x = scannerView.frame.origin.x, scanner_y = scannerView.frame.origin.y;
    
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, scannerView.frame.origin.x, body.frame.size.height)];
    leftView.backgroundColor = GRAYCOLOR;
    UIView *rightView = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(scannerView.frame), 0, body.frame.size.width-CGRectGetMaxX(scannerView.frame), body.frame.size.height)];
    rightView.backgroundColor = GRAYCOLOR;
    UIView *topView = [[UIView alloc]initWithFrame:CGRectMake(scannerView.frame.origin.x, 0, scannerView.frame.size.width, scannerView.frame.origin.y)];
    topView.backgroundColor = GRAYCOLOR;
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(scannerView.frame.origin.x, CGRectGetMaxY(scannerView.frame), scannerView.frame.size.width, body.frame.size.height-CGRectGetMaxY(scannerView.frame))];
    bottomView.backgroundColor = GRAYCOLOR;
    [body addSubview:leftView];
    [body addSubview:rightView];
    [body addSubview:topView];
    [body addSubview:bottomView];
    
    int line_thick = margin_3, line_long = line_thick * 8, middleLine_w = scannerView.frame.size.width - line_thick * 2;
    UIView *top_left = [[UIView alloc] init];
    top_left.frame = CGRectMake(scanner_x - line_thick, scanner_y - line_thick, line_long, line_thick);
    top_left.backgroundColor = GRAYCOLOR;
    [body addSubview:top_left];
    UIView *left_top = [[UIView alloc] init];
    left_top.frame = CGRectMake(scanner_x - line_thick, scanner_y - line_thick, line_thick, line_long);
    left_top.backgroundColor = GRAYCOLOR;
    [body addSubview:left_top];
    
    UIView *top_right = [[UIView alloc] init];
    top_right.frame = CGRectMake(CGRectGetMaxX(scannerView.frame) - (line_long - line_thick), scanner_y - line_thick, line_long, line_thick);
    top_right.backgroundColor = GRAYCOLOR;
    [body addSubview:top_right];
    UIView *right_top = [[UIView alloc] init];
    right_top.frame = CGRectMake(CGRectGetMaxX(scannerView.frame), scanner_y - line_thick, line_thick, line_long);
    right_top.backgroundColor = GRAYCOLOR;
    [body addSubview:right_top];
    
    UIView *bottom_left = [[UIView alloc] init];
    bottom_left.frame = CGRectMake(scanner_x - line_thick, CGRectGetMaxY(scannerView.frame), line_long, line_thick);
    bottom_left.backgroundColor = GRAYCOLOR;
    [body addSubview:bottom_left];
    UIView *left_bottom = [[UIView alloc] init];
    left_bottom.frame = CGRectMake(scanner_x - line_thick, CGRectGetMaxY(scannerView.frame) - (line_long - line_thick), line_thick, line_long);
    left_bottom.backgroundColor = GRAYCOLOR;
    [body addSubview:left_bottom];
    
    UIView *bottom_right = [[UIView alloc] init];
    bottom_right.frame = CGRectMake(CGRectGetMaxX(scannerView.frame) - (line_long - line_thick), CGRectGetMaxY(scannerView.frame), line_long, line_thick);
    bottom_right.backgroundColor =  GRAYCOLOR;
    [body addSubview:bottom_right];
    UIView *right_bottom = [[UIView alloc] init];
    right_bottom.frame = CGRectMake(CGRectGetMaxX(scannerView.frame), CGRectGetMaxY(scannerView.frame) - (line_long - line_thick), line_thick, line_long);
    right_bottom.backgroundColor = GRAYCOLOR;
    [body addSubview:right_bottom];
    
    middleLine = [[UIView alloc] init];
//    middleLine.image = [UIImage imageNamed:@"heda11"];
    middleLine.frame = CGRectMake(scanner_x + line_thick, scanner_y + line_thick, middleLine_w, 1);
    middleLine.backgroundColor = [UIColor grayColor];
    //    middleLine.backgroundColor = kSCAN_COLOR;
    [body addSubview:middleLine];
    
    UILabel *lblText = [[UILabel alloc] init];
    lblText.backgroundColor = [UIColor clearColor];
    NSString *text = @"将二维码放入框内，即可自动扫描";
    if (![ToolUtil isBlank:_tipsText]) {
        text = _tipsText;
    }
    CGSize size = [text sizeWithAttributes:@{NSFontAttributeName : FONT(14)}];
    lblText.frame = CGRectMake((WindowWidth - size.width) / 2, CGRectGetMaxY(scannerView.frame) + line_long * 2, size.width, size.height);
    lblText.text = text;
    [lblText setFont:FONT(14)];
    lblText.textColor = [UIColor whiteColor];
    [body addSubview:lblText];
}
// 中线走动的线程
- (void)timerThread {
    CGRect tempFrame = middleLine.frame;
    if (tempFrame.origin.y >= scannerView.frame.origin.y + tempFrame.size.height &&
        tempFrame.origin.y < CGRectGetMaxY(scannerView.frame) - tempFrame.size.height * 2) {
        tempFrame.origin.y += 1;
    } else {
        tempFrame.origin.y = scannerView.frame.origin.y + tempFrame.size.height;
    }
    middleLine.frame = tempFrame;
}


@end
